package sitemaps;

import java.io.File;
import java.io.FilenameFilter;
import java.util.Date;
import java.util.List;

public class SiteParser {
	
	private static final String SLASH = "/";
	private Sitemap site;
	private String path;
	final FilenameFilter filter; 
	final List<String> indexes;
	
	public SiteParser(final List<String> accepedExtensions, 
			final List<String> rejectedExtensions, final List<String> indexes) {
		filter = createFilter(accepedExtensions, rejectedExtensions);
		this.indexes = indexes;
	}

	private FilenameFilter createFilter(final List<String> accepedExtensions, final List<String> rejectedExtensions) {
		return new FilenameFilter() {
			public boolean accept(File dir, String name) {
				if(rejectedExtensions != null && rejectedExtensions.size() > 0) {
					for(String rejected1: rejectedExtensions)
						if(name.endsWith(rejected1))
							return false;
				}
				if(accepedExtensions != null && accepedExtensions.size() > 0) {
					for(String accepted1: accepedExtensions)
						if(name.endsWith(accepted1))
							return true;
					return false;
				}
				return true;
			}
		};
	}

	public Sitemap parseLocation(SitemapLocation location) {
		site = new Sitemap(location.getBaseUrl());
		path = "";
		final File baseFile = new File(location.getBasePath());
		if(baseFile.isDirectory()) {
			for(File file1: baseFile.listFiles()) {
				follow(file1, path);
			}
		}
		return site;
	}
	
	private void follow(File file, final String path) {
		final String filename = file.getName();
		final String loc = path + filename;
		if(file.isDirectory()) {
			final String path2 = loc + SLASH; 
			for(File file1: file.listFiles()) {
				follow(file1, path2);
			}
		} else {
			if(filter.accept(file, loc))
				site.add(isIndex(filename)? path:loc, 
						new Date(file.lastModified()));
		}
	}
	
	private boolean isIndex(String filename) {
		if(indexes != null)
			for(String index: indexes)
				if(filename.equals(index)) 
					return true;
		return false;
	}

}
